import type { UseFetchOptions } from 'nuxt/app'
import { showFailToast } from 'vant'
import { TT } from './token.js'
type Methods = 'GET' | 'POST' | 'DELETE' | 'PUT'

export interface IResultData<T> {
  code: number
  data: T
  success: boolean
  message: string
}

class HttpRequest {
  /* eslint-disable */
  handleError<T = any>(response: any) {
    const err = (text: string) => {
      showFailToast(response?._data?.message)
    }
    if (!response._data) {
      err('请求超时，服务器无响应！')
      return
    }
    const handleMap: { [key: number]: () => void } = {
      404: () => err('服务器资源不存在'),
      500: () => err('服务器内部错误'),
      403: () => err('没有权限访问该资源'),
      401: () => {
        err('登录状态已过期，需要重新登录')

        // TODO 跳转实际登录页
        navigateTo('/login')
      },
    }
    handleMap[response.status] ? handleMap[response.status]() : err('未知错误！')
  }

  request<T = any>(url: string, method: Methods, params: any, options?: UseFetchOptions<T>) {
    const that = this
    // const { baseURL } = useRuntimeConfig().public;
    const baseURL = 'https://uat-web.759pc.com/apiKK/'
    return new Promise((resolve, reject) => {
      const newOptions: UseFetchOptions<T> = {
        baseURL,
        method,
        ...options,
        onRequest({ request, options }) {
          // 设置请求头
          options.headers = options.headers || {}
          let token = useCookie('token')
          token.value = TT
          if (token?.value) {
            // @ts-ignore
            options.headers.Authorization = `Bearer ${token.value}`
          }
        },
        onRequestError({ request, options, error }) {
          // Handle the request errors
        },
        onResponse({ request, response, options }) {
          // Process the response data
          if (response._data.code !== 200) {
            that.handleError(response)
            return reject(response._data)
          }
          resolve(response._data)
        },
        onResponseError({ request, response, options }) {
          // Handle the response errors
        },
      }

      if (method === 'GET' || method === 'DELETE') {
        newOptions.params = params
      }
      if (method === 'POST' || method === 'PUT') {
        newOptions.body = params
      }
      useFetch(url, newOptions)
    })
  }

  // 封装常用方法

  get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
    return this.request(url, 'GET', params, options)
  }

  post<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
    return this.request(url, 'POST', data, options)
  }

  put<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
    return this.request(url, 'PUT', data, options)
  }

  delete<T = any>(url: string, params: any, options?: UseFetchOptions<T>) {
    return this.request(url, 'DELETE', params, options)
  }
}

const httpRequest = new HttpRequest()

export default httpRequest
